<?php

/**
 * index actions.
 *
 * @package    reduceri-cadouri
 * @subpackage index
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class indexActions extends sfActions
{
  public function preExecute()
  {
    $request = sfContext::getInstance()->getRequest();
    
    if(!$request->getParameter('city_name'))
    {
      if($request->getCookie('city_name'))
      {
        $request->setParameter('city_name',$request->getCookie('city_name'));
      }
      else
      {
        $request->setParameter('city_name','all');
      }
    }
    
    if(!$request->getParameter('category_name'))
    {
      $request->setParameter('category_name','all');
    }
    
    if(!$this->city = CityPeer::retrieveBySlug($request->getParameter('city_name')))
    {
      $request->setParameter('city_name','all');
      $this->city = new City();
      $this->city->setName('Romania');
    }
    
    $this->getResponse()->setCookie('city_name', $request->getParameter('city_name'), time()+60*60*24*7);
    
    $this->city_name = $request->getParameter('city_name');
    
    if(!$this->category = CategoryPeer::retrieveBySlug($request->getParameter('category_name')))
    {
      $request->setParameter('category_name','all');
    }
    $this->category_name = $request->getParameter('category_name');
  }
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    return $this->redirect('@city?city_name='.$request->getParameter('city_name').'&category_name='.$request->getParameter('category_name'));
  }
  
  public function executeCity(sfWebRequest $request)
  {
    $title = 'Reduceri & Cadouri';
    $keywords = 'reduceri, cadouri, promotii, oferte';
    $description = 'Cele mai mari reduceri';
      
    $c = new Criteria();
    $c->add(OfferPeer::ON_SITE, 1);
    $c->add(OfferPeer::START_TIME, date("Y-m-d H:i:s"), Criteria::LESS_EQUAL);
    $c->add(OfferPeer::END_TIME, date("Y-m-d H:i:s"), Criteria::GREATER_THAN);
    $c->addDescendingOrderByColumn(OfferPeer::PROMO);
    $c->addDescendingOrderByColumn(OfferPeer::DISCOUNT_PERCENT);
	  $c->addDescendingOrderByColumn(OfferPeer::CREATED_AT); 
    if($request->getParameter('category_name'))
    {
      if($category = CategoryPeer::retrieveBySlug($request->getParameter('category_name')))
      {
        $c->addJoin(OfferCategoryPeer::OFFER_ID, OfferPeer::ID);
        $c->add(OfferCategoryPeer::CATEGORY_ID, $category->getId());
        
        $title .= ' '.$category->getName();
        $description .= ' '.strtolower($category->getName());
        $keywords = strtolower($category->getName()).', '.$keywords;
      }
    }
    if($request->getParameter('city_name'))
    {
      if(!$this->city->isNew())
      {
        $c->addJoin(OfferCityPeer::OFFER_ID, OfferPeer::ID);
        $c->add(OfferCityPeer::CITY_ID, $this->city->getId());
        
        $title .= ' in '.$this->city->getName();
        $keywords = $this->city->getName().', '.$keywords;
        
      }
      $description .= ' din '.$this->city->getName();
    }
        
    $this->getResponse()->setTitle($title);
    $this->getResponse()->addMeta('keywords', $keywords);
    $this->getResponse()->addMeta('description', $description.' adunate intr-un singur loc! Alege si fa-ti un cadou tie sau cuiva drag!');
    
    $pager = new sfPropelPager('Offer', 10);
    $pager->setCriteria($c);
    $pager->setPage($this->getRequestParameter('page', 1));
    $pager->init();
    $this->pager = $pager;
    
    if(!$pager->getNbResults())
    {
      $this->getUser()->setFlash('notice', 'Ne pare rau, nu am gasit nici un rezultat.');
      return $this->redirect('@city?city_name='.$request->getParameter('city_name'));
    }
    
    $this->route_name = '@city';
    
    $this->setTemplate('index');
  }
  
  public function executeNew(sfWebRequest $request)
  {
    $c = new Criteria();
    $c->add(OfferPeer::ON_SITE, 1);
    $c->add(OfferPeer::START_TIME, date("Y-m-d H:i:s"), Criteria::LESS_EQUAL);
    $c->add(OfferPeer::END_TIME, date("Y-m-d H:i:s"), Criteria::GREATER_THAN);
    $c->addDescendingOrderByColumn(OfferPeer::CREATED_AT);
    $c->addDescendingOrderByColumn(OfferPeer::DISCOUNT_PERCENT);
    if($request->getParameter('city_name'))
    {
      if(!$this->city->isNew())
      {
        $c->addJoin(OfferCityPeer::OFFER_ID, OfferPeer::ID);
        $c->add(OfferCityPeer::CITY_ID, $this->city->getId());
        
        $this->getResponse()->setTitle('Reduceri & Cadouri in '.$this->city->getName());
        $this->getResponse()->addMeta('description', 'Cele mai mari reduceri din '.$this->city->getName().' adunate intr-un singur loc! Alege si fa-ti un cadou tie sau cuiva drag!');
        $this->getResponse()->addMeta('keywords', $this->city->getName().', reduceri, cadouri, promotii, oferte');
      }
    }
    $pager = new sfPropelPager('Offer', 10);
    $pager->setCriteria($c);
    $pager->setPage($this->getRequestParameter('page', 1));
    $pager->init();
    $this->pager = $pager;
    
    $this->route_name = '@reduceri_noi_city';
    
    $this->setTemplate('index');
  }
  
  public function executeExpired(sfWebRequest $request)
  {
    $c = new Criteria();
    $c->add(OfferPeer::ON_SITE, 1);
    $c->add(OfferPeer::END_TIME, date("Y-m-d H:i:s"), Criteria::LESS_EQUAL);
    $c->addDescendingOrderByColumn(OfferPeer::END_TIME);
    $c->addDescendingOrderByColumn(OfferPeer::START_TIME);
    if($request->getParameter('city_name'))
    {
      if(!$this->city->isNew())
      {
        $c->addJoin(OfferCityPeer::OFFER_ID, OfferPeer::ID);
        $c->add(OfferCityPeer::CITY_ID, $this->city->getId());
        
        $this->getResponse()->setTitle('Reduceri & Cadouri in '.$this->city->getName());
        $this->getResponse()->addMeta('description', 'Cele mai mari reduceri din '.$this->city->getName().' adunate intr-un singur loc! Alege si fa-ti un cadou tie sau cuiva drag!');
        $this->getResponse()->addMeta('keywords', $this->city->getName().', reduceri, cadouri, promotii, oferte');
      }
    }
    $pager = new sfPropelPager('Offer', 10);
    $pager->setCriteria($c);
    $pager->setPage($this->getRequestParameter('page', 1));
    $pager->init();
    $this->pager = $pager;
  }
  
  public function executeSite(sfWebRequest $request)
  {
    $this->forward404Unless($this->site = SitePeer::retrieveByPK($request->getparameter('site_id')));
    
    $c = new Criteria();
    $c->add(OfferPeer::SITE_ID, $this->site->getId());
    $c->add(OfferPeer::ON_SITE, 1);
    $c->add(OfferPeer::START_TIME, date("Y-m-d H:i:s"), Criteria::LESS_EQUAL);
    $c->add(OfferPeer::END_TIME, date("Y-m-d H:i:s"), Criteria::GREATER_THAN);
    if($request->getParameter('city_name'))
    {
      if(!$this->city->isNew())
      {
        $c->addJoin(OfferCityPeer::OFFER_ID, OfferPeer::ID);
        $c->add(OfferCityPeer::CITY_ID, $this->city->getId());
      }
    }
    $c->addDescendingOrderByColumn(OfferPeer::DISCOUNT_PERCENT);
	  $c->addDescendingOrderByColumn(OfferPeer::CREATED_AT); 
    
    $pager = new sfPropelPager('Offer', 10);
    $pager->setCriteria($c);
    $pager->setPage($this->getRequestParameter('page', 1));
    $pager->init();
    $this->pager = $pager;
    
    $this->route_name = '@site_city';
  }
  
  public function executeLogin(sfWebRequest $request)
  {
    if($request->getCookie('lr') == 'lopoIun0Oo9i8')
    {
      $this->getResponse()->setCookie('lr', 'lopoIun0Oo9i8', time()+60*60*24*30, '/'); // 30 days  
      $this->getUser()->setAuthenticated(true);
      return $this->redirect('@homepage');
    }  
    
    $this->form = new LoginForm();
    
    if($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('login'));
      if($this->form->isValid())
      {
        $this->getUser()->setAuthenticated(true);
        
        if($this->form->getValue('remember'))
        {
          $this->getResponse()->setCookie('lr', 'lopoIun0Oo9i8', time()+60*60*24*30, '/'); // 30 days
        }
        
        return $this->redirect('@homepage');
      }
    }
  }
  
  public function executeLogout(sfWebRequest $request)
  {
    $this->getUser()->setAuthenticated(false);
    
    return $this->redirect('@homepage');
  }
  
  public function executeContact(sfWebRequest $request)
  {
    $this->form = new ContactForm();
    
    if($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('contact'));
      if($this->form->isValid())
      {
        $date = date("d/m/Y H:i:s");
        $bodyText = <<<EOF
Nume: {$this->form->getValue('name')}
Email: {$this->form->getValue('email')}
Mesaj:
{$this->form->getValue('message')}

Data: {$date}
EOF;
        
        $this->getMailer()->composeAndSend(
          'website@reduceri-cadouri.ro',
          'admin@reduceri-cadouri.ro',
          'Mesaj Contact',
          $bodyText
        );
        
        $this->getUser()->setFlash('notice', 'Multumim pentru mesaj!');
        return $this->redirect('@contact');
      }
    }
  }
  
  public function executeClearcache(sfWebRequest $request)
  {
    $dir = sfConfig::get('sf_cache_dir').DIRECTORY_SEPARATOR.'frontend';
    if(file_exists($dir))
    {
          Utils::deleteDirectory($dir);
    }

    return $this->redirect('@homepage');
  }
  
  public function executeError404(sfWebRequest $request)
  {
    
  }
  
  public function executeSearch(sfWebRequest $request)
  {
    if($request->isMethod('post'))
    {
      if($query = $request->getParameter('query'))
      {
        return $this->redirect('@cauta1?query='.$query);
      }
    }
    
    mb_internal_encoding("UTF-8");
    mb_regex_encoding("UTF-8");

    $query = $request->getParameter('query');
    $query = Utils::transliterateString(mb_strtolower($query));
    $query = trim($query);
    //$query = mb_ereg_replace('[^a-z0-9%]', ' ', $query);
    //$query = mb_ereg_replace('[[:space:]]+', ' ', $query);

    if(strlen($query) < 3)
    {
      $this->getUser()->setFlash('notice', 'Te rugam introdu cel putin 3 caractere pentru cautare');
      return $this->redirect('@city?city_name='.$request->getParameter('city_name'));
    }
    
    if(strlen($query) > 30)
    {
      $this->getUser()->setFlash('notice', 'Te rugam introdu cel mult 30 de caractere pentru cautare');
      return $this->redirect('@city?city_name='.$request->getParameter('city_name'));
    }
 
    $this->getResponse()->setTitle('Reduceri & Cadouri: '.$query);
    
    $this->count_offers = OfferPeer::countForLuceneQuery($query, $request->getParameter('city_name'));
    $this->page = $request->getParameter('page', 1);
    $this->first_page = 1;
    $this->last_page = ceil($this->count_offers / 10);
    $this->pages = array();
    
    for($i = 1; $i <= ceil($this->count_offers / 10); $i++)
    {
      $this->pages[] = $i;
    }
    
    if($this->page < 1)
    {
      $this->page = 1;
    }
    if($this->page > ceil($this->count_offers / 10))
    {
      $this->page = ceil($this->count_offers / 10);
    }
    $this->previous_page = $this->page - 1 > 0 ? $this->page - 1 : 1;
    $this->next_page = $this->page + 1 < $this->last_page ? $this->page + 1 : $this->last_page;
    
    $this->offers = OfferPeer::getForLuceneQuery($query, 10, ($this->page - 1) * 10, $request->getParameter('city_name'));

    if(!count($this->offers))
    {
      $this->getUser()->setFlash('notice', 'Ne pare rau, nu am gasit nici un rezultat.');
      return $this->redirect('@city?city_name='.$request->getParameter('city_name'));
    }
    
    if($this->page == 1)
    {
      $search_keyword = new SearchKeyword();
      $search_keyword->setKeyword($query);
      $search_keyword->setResults($this->count_offers);
      $search_keyword->save();
    }
    
    $this->query = $query;
  }
}
